# -*- coding: utf-8 -*-

from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp import SUPERUSER_ID
from openerp.report.render.rml2pdf import customfonts
import openerp
import pytz


import os
import sys
import jinja2
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import StringIO
import time
import datetime
import werkzeug.utils
import httplib
import urllib
import simplejson

from openerp.addons.jst_website_ext.pools import ModelPool, CursorProxy, common_functions, PageProxy
from openerp.addons.website.controllers.main import Website

##############################################
# 模板配置
##############################################
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.jst_website_ext', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


##############################################
# 商城请求
##############################################
class JST_Website(Website):
    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps

    @http.route('/', type='http', auth='public', website=True)
    def index(self, **kw):
        template = env.get_template("index.html")
        return template.render(kw)



###################################################
# 中文排序
###################################################
#import re

current_path = os.path.split(os.path.realpath(__file__))[0]
# 建立拼音辞典
def load_py_dict():
    dic_py = dict()
    f_py = open(current_path + '/py.txt',"r")
    content_py = f_py.read()
    lines_py = content_py.split('\n')
    n=len(lines_py)
    for i in range(0,n-1):
        word_py, mean_py = lines_py[i].split('\t', 1)#将line用\t进行分割，最多分一次变成两块，保存到word和mean中去
        dic_py[word_py]=mean_py
    f_py.close()

    # 建立笔画辞典
    dic_bh = dict()
    f_bh = open(current_path + '/bh.txt',"r")
    content_bh = f_bh.read()
    lines_bh = content_bh.split('\n')
    n=len(lines_bh)
    for i in range(0,n-1):
        word_bh, mean_bh = lines_bh[i].split('\t', 1)#将line用\t进行分割，最多分一次变成两块，保存到word和mean中去
        dic_bh[word_bh] = mean_bh
    f_bh.close()
    return dic_py, dic_bh


dic_py, dic_bh = load_py_dict()

# 辞典查找函数
def searchdict(dic,uchar):
    if isinstance(uchar, str):
        uchar = unicode(uchar,'utf-8')
    if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
        value=dic.get(uchar.encode('utf-8'))
        if value == None:
            value = '*'
    else:
        value = uchar
    return value

#比较单个字符
def comp_char_PY(A,B):
    if A==B:
        return -1
    pyA=searchdict(dic_py,A)
    pyB=searchdict(dic_py,B)
    if pyA > pyB:
        return 1
    elif pyA < pyB:
        return 0
    else:
        bhA=eval(searchdict(dic_bh,A))
        bhB=eval(searchdict(dic_bh,B))
        if bhA > bhB:
            return 1
        elif bhA < bhB:
            return 0
        else:
            return "Are you kidding?"

#比较字符串
def comp_char(A,B):
    charA = A.decode("utf-8")
    charB = B.decode("utf-8")
    n=min(len(charA),len(charB))
    i=0
    while i < n:
        dd=comp_char_PY(charA[i],charB[i])
        if dd == -1:
            i=i+1
            if i==n:
                dd=len(charA)>len(charB)
        else:
            break
    return dd

# 排序函数
def cnsort(lines):
    n = len(lines)
    #lines="\n".join(lines)
    for i in range(1, n):  # 插入法
        tmp = lines[i]
        j = i
        while j > 0 and comp_char(lines[j-1]['name'], tmp['name']):
            lines[j] = lines[j-1]
            j -= 1
        lines[j] = tmp
    return lines

class WebsiteExchange(http.Controller):
    @http.route('/kaquan/index', auth='public', website=True)
    def card_exchange_index(self, **kw):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        #是否微信查询
        chaxun = kw.get('chaxun')
        #记录刷新页面时的时间
        http.request.session.open_time = time.time()
        #session中取得openid，如果有的话
        openid = http.request.session.openid
        #查询此openid的兑换记录
        apply_delivery = registry.get('apply.delivery')
        values = {'chaxun': chaxun, 'openid': openid}
        if openid:
            exchange_ids = apply_delivery.search(cr, SUPERUSER_ID, [('openid', '=', openid)])
            values['exchanges'] = apply_delivery.browse(cr, SUPERUSER_ID, exchange_ids)

        #return http.request.website.render('website_exchange.index', values)
        template = env.get_template("kaquan.html")
        return template.render(values)

    @http.route('/kaquan/verify', auth='public', website=True)
    def card_exchange_verify(self, card_code, card_password, validate_code):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context
        #检查验证码
        session_validate_code = http.request.session.validate_code
        if session_validate_code:
            session_validate_code = session_validate_code.lower()
        if not validate_code or session_validate_code != validate_code.lower():
            kw = {'validate_code_error': 1}
            return werkzeug.utils.redirect('/kaquan/index' + '?' + urllib.urlencode(kw))

        #检查卡券密码
        cr.execute('SELECT id, is_active, is_enabled, is_exchanged FROM product_card_line WHERE code=%s'
                   , (card_code,))
        card = cr.dictfetchone()
        if card:
            cr.execute("SELECT * FROM product_card_password WHERE line_id=%s", (card['id'],))
            password = cr.dictfetchone()['password']
            if card_password != password:
                card = None

        if not card:
            kw = {'code_or_password_error': 1}
            return werkzeug.utils.redirect('/kaquan/index' + '?' + urllib.urlencode(kw))

        if not card['is_active']:
            kw = {'is_active_error': 1}
            return werkzeug.utils.redirect('/kaquan/index' + '?' + urllib.urlencode(kw))

        if not card['is_enabled']:
            kw = {'is_enabled_error': 1}
            return werkzeug.utils.redirect('/kaquan/index' + '?' + urllib.urlencode(kw))

        #放入session中
        request.session.card_code = card_code
        if card['is_exchanged']:
            return werkzeug.utils.redirect('/kaquan/info')
        else:
            return werkzeug.utils.redirect('/kaquan/new')

    #验证码校验
    @http.route('/kaquan/validate_code_verify', auth='public', website=True)
    def card_exchange_validate_code_verify(self, validate_code):
        #检查验证码
        session_validate_code = http.request.session.validate_code
        if session_validate_code:
            session_validate_code = session_validate_code.lower()
        if not validate_code or session_validate_code != validate_code.lower():
            return 'false'
        return 'true'

    #卡券兑换新增
    @staticmethod
    def card_exchange_save(args):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        result = 0
        #从session中取得卡号
        card_code = request.session.card_code
        #从session中取得openid
        openid = request.session.openid
        cr.execute('SELECT id, is_active, is_enabled, is_exchanged, product_id FROM product_card_line WHERE code=%s', (card_code,))
        card = cr.dictfetchone()
        #如果卡券编号存在且已激活且已启用且没有兑换
        if card and card['is_active'] and card['is_enabled'] and not card['is_exchanged']:
            #取得密码
            cr.execute("SELECT password FROM product_card_password WHERE line_id=%s" % (card['id'],))
            password = cr.dictfetchone()['password']
            product_card_track = registry.get('product.card.track')
            apply_delivery = registry.get('apply.delivery')
            #建立兑换记录
            #apply_delivery.create时会自动建立track记录
            result = apply_delivery.create(cr, SUPERUSER_ID, {
                'code': card['id'],
                'copy_code': card_code,
                'password': password,
                'product_id': card['product_id'],
                'province': args.get('province'),
                'city': args.get('city'),
                'country': args.get('county'),
                'address': args.get('address'),
                'postal_code': args.get('postal_code'),
                'to_name': args.get('to_name'),
                'ship_memo': args.get('ship_memo'),
                'mobile_number': args.get('mobile_number'),
                'phone_number': args.get('phone_number'),
                'estimated_ship_date': args.get('delivery_date'),
                'openid': openid
            })
            #更新卡券兑换状态为已兑换
            cr.execute('UPDATE product_card_line SET is_exchanged=true WHERE id=%s', (card['id'],))

        #返回兑换记录主键
        return result

    @http.route('/kaquan/new', auth='public', website=True)
    def card_exchange_new(self, **kw):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        values = kw
        message = []

        #起始发货日期
        config_start_delivery_date_string = registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'estimated_ship_start_date') or '2015-09-01'
        #结束发货日期
        config_end_delivery_date_string = registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'estimated_ship_end_date') or '2016-02-01'

        config_start_delivery_date = datetime.datetime.strptime(config_start_delivery_date_string +\
                                                                ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        #config_start_delivery_date = config_start_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))

        config_end_delivery_date = datetime.datetime.strptime(config_end_delivery_date_string +\
                                                              ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        #config_end_delivery_date = config_end_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))

        now = datetime.datetime.now()
        #如果提货起始时间比当天后的第三天晚，则从提货起始时间开始，否则起始选择时间为当第三天
        start_delivery_date = now + datetime.timedelta(hours=8) + datetime.timedelta(days=1)
        #start_delivery_date = start_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
        start_delivery_date = datetime.datetime(start_delivery_date.year, start_delivery_date.month, start_delivery_date.day, 00, 00, 00)
        if config_start_delivery_date > start_delivery_date:
            start_delivery_date = config_start_delivery_date

        #如果提交了兑换请求
        if kw.get('submit') == 'exchange':
            #检查提交内容
            if not values.get('to_name'):
                message.append(u'请输入收货人姓名')
            if not values.get('mobile_number') and not values.get('phone_number'):
                message.append(u'请填写手机号码或者电话号码至少一个')
            if not values.get('delivery_date'):
                message.append(u'请选择期望发货日期')
            if not values.get('province'):
                message.append(u'请选择省市')
            if not values.get('city'):
                message.append(u'请选择市')
            if not values.get('county'):
                message.append(u'请选县区')
            if not values.get('address'):
                message.append(u'请输入街道门牌地址')
            else:
                try:
                    input_delivery_date = datetime.datetime.strptime(values.get('delivery_date') +\
                                                                ' 07:07:07', '%Y-%m-%d %H:%M:%S')
                    #input_delivery_date = input_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
                    #如果早于配置的起始选择时间，则提示错误
                    if input_delivery_date < start_delivery_date:
                        message.append(u'选择的期望发货日期不能早于' + start_delivery_date.strftime('%Y-%m-%d'))
                    if input_delivery_date > config_end_delivery_date:
                        message.append(u'选择的期望发货日期不能晚于' + config_end_delivery_date_string)
                except ValueError as ve:
                    message.append(u'日期格式不正确, 需要减号隔开年月日，如: 2016-01-01')

            if not message:
                result = WebsiteExchange.card_exchange_save(kw)
                if result:
                    return werkzeug.utils.redirect('/kaquan/info' + '?exchange_ok=1')
                else:
                    message.append(u'卡券提货记录保存失败，请联系客服')

        #从session中取得卡号
        card_code = request.session.card_code

        #取得省份列表
        cr.execute('SELECT rcs.id, rcs.name FROM res_country_state rcs '\
                   'INNER JOIN res_country rc ON rc.id=rcs.country_id '\
                   'WHERE rc.name=%s', ('China',))
        provinces = cr.dictfetchall()
        #省份列表按中文读音排序
        provinces_sorted = cnsort(provinces)

        #如果有选择省份，则取得城市列表
        values['cities'] = []
        if kw.get('province'):
            cr.execute('SELECT id, city_name as name FROM all_city WHERE province_name=%s', (kw.get('province'),))
            values['cities'] = cr.dictfetchall()
            values['cities'] = cnsort(values['cities'])
        #如果有选择城市，则取得市县列表
        values['counties'] = []
        if kw.get('city'):
            cr.execute('SELECT id, county_name as name FROM all_country WHERE city_name=%s', (kw.get('city'),))
            values['counties'] = cr.dictfetchall()
            values['counties'] = cnsort(values['counties'])

        #如果微信电子卡券提货，需要微信电子卡券核销，也就是form需要提交到微信提货模块去处理
        values['form_action'] = '/kaquan/new'
        if kw.get('card_id'):
            values['form_action'] = '/wx/kaquan'
            #进行激活操作
            product_card_obj = registry.get('product.card.line')
            # 找到对应的卡券IDS
            card_ids = product_card_obj.search(cr, SUPERUSER_ID, [('code', 'in', [card_code])])
            if card_ids:
                card = product_card_obj.browse(cr, SUPERUSER_ID, card_ids[0])
                if not card.is_active:
                    # 激活卡券
                    product_card_obj = registry.get('product.card.line')
                    try:
                        product_card_obj.do_active(cr, SUPERUSER_ID, card_ids)
                    except openerp.exceptions.except_orm as e:
                        cr.rollback()
                        _logger.error(u'微信电子卡券激活失败: %s' % e[1])
                        #message.append(u'卡券无法激活，请联系客服4007285757')

        #取得卡券对应的产品名称
        cr.execute('SELECT id, is_active, is_enabled, is_exchanged, product_id FROM product_card_line WHERE code=%s',
                   (card_code,))
        card = cr.dictfetchone()
        product_name = ''
        if card:
            cr.execute('SELECT name_template FROM product_product WHERE id=%s', (card['product_id'],))
            product_name = cr.dictfetchone()['name_template']

        #values['debug'] = True
        #设置发日期默认值
        if not values.get('delivery_date'):
            values['delivery_date'] = start_delivery_date.strftime('%Y-%m-%d')
        values['message'] = "<br/>".join(message)
        values['card'] = card
        values['product_name'] = product_name
        values['provinces'] = provinces_sorted
        values['start_delivery_date'] = start_delivery_date.strftime('%Y-%m-%d')
        values['end_delivery_date'] = config_end_delivery_date.strftime('%Y-%m-%d')
        #return http.request.website.render('website_exchange.new', values)
        template = env.get_template("songhuo.html")
        return template.render(values)

    #快递查询接口
    def _query_express(self, com, code):
        data = {'key': '5fbcf971bb5747c29af561f2a2186ec0', 'com': com, 'no': code}
        params = urllib.urlencode(data)
        json_string = u'{}'

        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        try:
            http_client = httplib.HTTPConnection("apis.haoservice.com", timeout=60)
            http_client.request("POST", "/lifeservice/exp", params, headers)

            response = http_client.getresponse()
            if response.status == 200:
                json_string = response.read()
        finally:
            if http_client:
                http_client.close()

        return json_string

    @http.route('/kaquan/express-delivery-detail', auth='public', website=True)
    def card_exchange_express_delivery_detail(self, shipping_type, shipping_code):
        json_string = self._query_express(shipping_type, shipping_code)
        json_data = simplejson.loads(json_string)
        #如果正确，则返回快递详细信息
        if json_data.get('error_code') == 0:
            express_result = json_data.get('result')
            if express_result:
                result_list = express_result.get('data')
                result_html = ''
                for line in result_list:
                    result_html += line.get('time') + '<br />' + line.get('context') + '<br />\n'
                return result_html
        #如果有错误，则返回错误信息
        else:
            return json_data.get('reason')
        #return json_string

    @http.route('/kaquan/info', auth='public', website=True)
    def card_exchange_info(self, **kw):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context
        card_code = kw.get('card_code')
        need_check_openid = False
        if card_code:
            openid = http.request.session.openid
            need_check_openid = True
            #检查传入的卡券号码是否合法
        else:
            card_code = request.session.card_code
        cr.execute('SELECT * FROM product_card_line WHERE code=%s', (card_code,))
        card = cr.dictfetchone()
        exchange = {}
        if card and card['is_exchanged']:
            if need_check_openid:
                cr.execute("SELECT * FROM apply_delivery WHERE code=%s AND openid=%s", (card['id'], openid))
            else:
                cr.execute("SELECT * FROM apply_delivery WHERE code=%s", (card['id'],))
            exchange = cr.dictfetchone()
            if exchange:
                exchange['province_name'] = ''
                exchange['city_name'] = ''
                exchange['county_name'] = ''
                #取得产品名称
                cr.execute('SELECT name_template FROM product_product WHERE id=%s', (card['product_id'],))
                product_name = cr.dictfetchone()['name_template']
                exchange['product_name'] = product_name
                #取得省市县名称
                if exchange.get('province'):
                    cr.execute('SELECT name FROM res_country_state WHERE id=%s', (exchange['province'],))
                    exchange['province_name'] = cr.dictfetchone()['name']
                if exchange.get('city'):
                    cr.execute('SELECT city_name FROM all_city WHERE id=%s', (exchange['city'],))
                    exchange['city_name'] = cr.dictfetchone()['city_name']
                if exchange.get('country'):
                    cr.execute('SELECT county_name FROM all_country WHERE id=%s', (exchange['country'],))
                    exchange['county_name'] = cr.dictfetchone()['county_name']
                #如果有货运类型
                if exchange['shipping_type']:
                    cr.execute("SELECT name, description FROM express_type WHERE id=%s", (exchange['shipping_type'],))
                    express_type = cr.dictfetchone()
                    if express_type:
                        exchange['express_type_name'] = express_type['name']
                        exchange['express_type_com'] = express_type['description']
                        #if express_type_code and shipping_code:
                            #调用查询快递接口
                            #self._query_express(express_type_code, shipping_code)

        #return http.request.website.render('website_exchange.info', )
        template = env.get_template("info.html")
        return template.render({
            'card': card,
            'exchange': exchange,
            'exchange_ok': kw.get('exchange_ok')
        })


    @http.route('/kaquan/get_cities', auth='public', website=True, type="json")
    def get_cities(self, province_id):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context

        cr.execute('SELECT id, city_name as name FROM all_city '\
                   'WHERE province_name=%s', (province_id,))
        cities = cr.dictfetchall()

        cities_sorted = cnsort(cities)

        return cities_sorted

    @http.route('/kaquan/get_counties', auth='public', website=True, type="json")
    def get_counties(self, city_id):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context

        cr.execute('SELECT id, county_name as name FROM all_country '\
                   'WHERE city_name=%s', (city_id,))
        counties = cr.dictfetchall()

        counties_sorted = cnsort(counties)

        return counties_sorted

#定制菜单貌似有bug，继承并覆盖
#sign菜单由于权限是public，导致无法定制
class Website(openerp.addons.website.controllers.main.Website):
    @http.route('/website/customize_template_get', type='json', auth='user', website=True)
    def customize_template_get(self, xml_id, full=False):
        """ Lists the templates customizing ``xml_id``. By default, only
        returns optional templates (which can be toggled on and off), if
        ``full=True`` returns all templates customizing ``xml_id``
        """
        imd = request.registry['ir.model.data']
        view_model, view_theme_id = imd.get_object_reference(
            request.cr, request.uid, 'website', 'theme')

        user = request.registry['res.users']\
            .browse(request.cr, request.uid, request.uid, request.context)
        user_groups = set(user.groups_id)

        views = request.registry["ir.ui.view"]\
            ._views_get(request.cr, request.uid, xml_id, context=dict(request.context or {}, active_test=False))
        done = set()
        result = []
        for v in views:
            #有些view用户组是public的，当前用户组却肯定不含有public权限，导致判断错误
            # if not user_groups.issuperset(v.groups_id):
            #     continue
            if full or (v.customize_show and v.inherit_id.id != view_theme_id):
                if v.inherit_id not in done:
                    result.append({
                        'name': v.inherit_id.name,
                        'id': v.id,
                        'xml_id': v.xml_id,
                        'inherit_id': v.inherit_id.id,
                        'header': True,
                        'active': False
                    })
                    done.add(v.inherit_id)
                result.append({
                    'name': v.name,
                    'id': v.id,
                    'xml_id': v.xml_id,
                    'inherit_id': v.inherit_id.id,
                    'header': False,
                    'active': v.active,
                })
        return result